﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;

public partial class ContactUSEditEN : System.Web.UI.Page
{

    public List<ContactUS> lstContactUSGrid
    {
        get
        {
            if (ViewState["lstContactUSGrid"] == null)
            {
                ViewState["lstContactUSGrid"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["lstContactUSGrid"].ToString()] == null)
            {
                Session[ViewState["lstContactUSGrid"].ToString()] = new List<ContactUS>();

            }

            return (List<ContactUS>)Session[ViewState["lstContactUSGrid"].ToString()];

        }
        set
        {
            if (ViewState["lstContactUSGrid"] == null)
            {
                ViewState["lstContactUSGrid"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["lstContactUSGrid"].ToString()] = value;
        }   
   
   

    }




    long mContactUSID
    {
        get
        {
            if (ViewState["mContactUSID"] == null)
            {
                ViewState["mContactUSID"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mContactUSID"].ToString()] == null)
            {
                long obj = -1;
                Session[ViewState["mContactUSID"].ToString()] = obj;

            }

            return (long)Session[ViewState["mContactUSID"].ToString()];

        }
        set
        {
            if (ViewState["mContactUSID"] == null)
            {
                ViewState["mContactUSID"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mContactUSID"].ToString()] = value;
        }
    }


    ContactUS mObjContactUS
    {
        get
        {
            if (ViewState["mObjContactUS"] == null)
            {
                ViewState["mObjContactUS"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mObjContactUS"].ToString()] == null)
            {
                Session[ViewState["mObjContactUS"].ToString()] = new ContactUS();

            }

            return (ContactUS)Session[ViewState["mObjContactUS"].ToString()];

        }
        set
        {
            if (ViewState["mObjContactUS"] == null)
            {
                ViewState["mObjContactUS"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mObjContactUS"].ToString()] = value;
        }
    }






    protected void Page_Load(object sender, EventArgs e)
    {



        Persons objPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objPersons);
       
        if (!Page.IsPostBack)
        {
            
            bindGrid("");
            editLoad();
        }

        

    }



    /// <summary>
    /// this function will bind the grid 
    /// </summary>
    protected void bindGrid(string strIn)
    {

        List<ContactUS> lstContactUS = search(strIn);



        lstContactUSGrid = lstContactUS;

        grdUsers.DataSource = lstContactUS;
        grdUsers.DataBind();
    }



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Contact_us_edit_page))
            Response.Redirect("LoginEN.aspx");


        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_contact_us_edit_page))
        {
            btnSave.Enabled = false;
            btnDelete.Enabled = false;
        }
       




    }
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {

        bindGrid(txtSearch.Text);
       
    }

    /// <summary>
    /// this function will search in cards and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of types matched</returns>
    protected List<ContactUS> search(string txtText)
    {
        ContactUSDB objContactUSDB = new ContactUSDB(ConnectionStrings.LMS);
        List<ContactUS> lstRet = new List<ContactUS>();
        if (txtText.Trim() == "")
        {
            List<ContactUS> lstNew = objContactUSDB.Select(" top 100 ", " order by [ContactTitleEN] ");
            //lstNew = new List<TicketType>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            //no status
            return lstNew;
        }

        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }

        foreach (string strValue in strValues)
        {
            ContactUS objContactUS = new ContactUS();
            objContactUS.ContactTitleAR = objContactUS.ContactTitleEN = objContactUS.Email1 = objContactUS.Email2 = objContactUS.InnerPhone1 = 
                objContactUS.InnerPhone2 = objContactUS.Phone1 = objContactUS.Phone2 = objContactUS.Mobile1 = objContactUS.Mobile2 = "%" + strValue + "%";
            List<ContactUS> lstContactUS = objContactUSDB.SearchOrLike(objContactUS);
            //lstTicketType = new List<TicketType>(from objFol in lstTicketType where objFol.StatusID != 2 select objFol);
            //no status
            foreach (ContactUS objFol in lstContactUS)
            {
                if ((from objIn in lstRet where objIn.ID == objFol.ID select objIn).ToList().Count == 0)
                {
                    lstRet.Add(objFol);
                }
            }

        }


        return lstRet;



    }





    protected void grdUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);

        //security check

        if (!objCurrentPersons.lstAllRulesIDs.Contains((long)RulesEnum.Editing_contact_us_edit_page))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }


        long ContactUSID = long.Parse(grdUsers.DataKeys[e.RowIndex]["ID"].ToString());



        ContactUSDB objContactUSDB = new ContactUSDB(ConnectionStrings.LMS);
        List<ContactUS> lstContactUS = objContactUSDB.getContactUSByID(ContactUSID);




        if (lstContactUS.Count == 0)
        {
            lblError.Text = "No cards to delete";
            lblResult.Text = "";
            return;
        }





        


        objContactUSDB.Delete(lstContactUS[0]);



        lblResult.Text = "Deleted ok.";



        bindGrid(txtSearch.Text);



    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        clearAllControls();
    }
    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstContactUSGrid;
        grdUsers.PageIndex = e.NewPageIndex;

        grdUsers.DataBind(); 
    }


    /// <summary>
    /// this function will check mContactUSID to detect update or insert
    /// </summary>
    protected void checkID()
    {
        if (mContactUSID != -1)
        {
            try
            {

                ContactUSDB objContactUSDB = new ContactUSDB(ConnectionStrings.LMS);
                List<ContactUS> lstContactUS = objContactUSDB.getContactUSByID(mContactUSID);
                if (lstContactUS.Count > 0)
                {


                    mObjContactUS = lstContactUS[0];
                    btnDelete.Visible = true;

                }
                else
                {
                    mContactUSID = ((long)-1);
                    
                }


            }
            catch
            {
                mContactUSID = ((long)-1);
            }


            
        }
        else
        {
            btnDelete.Visible = false;

        }
    }



    /// <summary>
    /// this will bind the cards data to update or delete
    /// </summary>
    protected void BindAllControls()
    {
        if (mContactUSID != -1)
        {

            txtContactTitleAR.Text = mObjContactUS.ContactTitleAR;
            txtContactTitleEN.Text = mObjContactUS.ContactTitleEN;
            txtEmail1.Text = mObjContactUS.Email1;
            txtEmail2.Text = mObjContactUS.Email2;
            txtInnerPhone1.Text = mObjContactUS.InnerPhone1;
            txtInnerPhone2.Text = mObjContactUS.InnerPhone2;
            txtMobile1.Text = mObjContactUS.Mobile1;
            txtMobile2.Text = mObjContactUS.Mobile2;
            txtPhone1.Text = mObjContactUS.Phone1;
            txtPhone2.Text = mObjContactUS.Phone2;
            
            

        }
    }



    /// <summary>
    /// this function will read all controls values
    /// </summary>
    protected void ReadAllControls()
    {

        mObjContactUS.ContactTitleAR = txtContactTitleAR.Text;
        mObjContactUS.ContactTitleEN = txtContactTitleEN.Text;
        mObjContactUS.Email1 = txtEmail1.Text;
        mObjContactUS.Email2 = txtEmail2.Text;
        mObjContactUS.InnerPhone1 = txtInnerPhone1.Text;
        mObjContactUS.InnerPhone2 = txtInnerPhone2.Text;
        mObjContactUS.Mobile1 = txtMobile1.Text;
        mObjContactUS.Mobile2 = txtMobile2.Text;
        mObjContactUS.Phone1 = txtPhone1.Text;
        mObjContactUS.Phone2 = txtPhone2.Text;
        


    }



    /// <summary>
    /// this function for clearing controls
    /// </summary>
    protected void clearAllControls()
    {

        txtContactTitleAR.Text = "";
        txtContactTitleEN.Text = "";
        txtEmail1.Text = "";
        txtEmail2.Text = "";
        txtInnerPhone1.Text = "";
        txtInnerPhone2.Text = "";
        txtMobile1.Text = "";
        txtMobile2.Text = "";
        txtPhone1.Text = "";
        txtPhone2.Text = "";

        mObjContactUS = new ContactUS();

        mContactUSID = -1;

    }



    /// <summary>
    /// this function for loading the editing behavior
    /// </summary>
    protected void editLoad()
    {


        Persons currentPerson = GlobalVars.getCurrentPerson();




       

            checkSecurityAndCustomizePage(currentPerson);

            checkID();


            BindAllControls();




        
    }



    /// <summary>
    /// this function will Save the card
    /// </summary>
    protected void Save()
    {


        if (checkForRepeats())
        {
            ContactUSDB objContactUSDB = new ContactUSDB(ConnectionStrings.LMS);
            if (mObjContactUS.ID == -1)
            {
                objContactUSDB.Insert(mObjContactUS);
                clearAllControls();
                bindGrid(txtSearch.Text);
                lblResult.Text = "Data saved ok.";
            }
            else
            {
                objContactUSDB.Update(mObjContactUS);
                bindGrid(txtSearch.Text);
                BindAllControls();
                lblResult.Text = "Data saved ok.";

            }



        }


    }


    /// <summary>
    /// this function will check if the card exist with the same Name or not
    /// </summary>
    /// <returns>true if ok , false for error (card exist before)</returns>
    protected bool checkForRepeats()
    {
        ContactUSDB objContactUSDB = new ContactUSDB(ConnectionStrings.LMS);



        List<ContactUS> lstOldContactUS = objContactUSDB.getContactUSByContactTitleAR (mObjContactUS.ContactTitleAR);

        List<ContactUS> lstExist = new List<ContactUS>(from objOrg in lstOldContactUS where (objOrg.ContactTitleAR == mObjContactUS.ContactTitleAR && objOrg.ID != mObjContactUS.ID) select objOrg);

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }


        lstOldContactUS = objContactUSDB.getContactUSByContactTitleEN(mObjContactUS.ContactTitleEN);

        lstExist = new List<ContactUS>(from objOrg in lstOldContactUS where (objOrg.ContactTitleEN == mObjContactUS.ContactTitleEN && objOrg.ID != mObjContactUS.ID) select objOrg);

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }





        return true;

    }




    /// <summary>
    /// this function will show a message with the error for existense
    /// </summary>
    private void errorExist()
    {

        lblError.Text = "Error , a card with the same title  is already found , choose a new Name";

    }



    protected void btnSave_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_contact_us_edit_page))
            return;


        if (Page.IsValid)
        {



            ReadAllControls();






            Save();


        }
    }




    protected void btnDelete_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_contact_us_edit_page))
            return;


        ReadAllControls();


        long ContactUSID = mContactUSID;




        ContactUSDB objContactUSDB = new ContactUSDB(ConnectionStrings.LMS);
        List<ContactUS> lstContactUS = objContactUSDB.getContactUSByID(ContactUSID);




        if (lstContactUS.Count == 0)
        {
            lblError.Text = "No cards to delete";
            lblResult.Text = "";
            return;
        }





        

        objContactUSDB.Delete(lstContactUS[0]);


        bindGrid(txtSearch.Text);
        lblResult.Text = "Deleted ok.";



        

        clearAllControls();






    }




    protected void grdUsers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);



        long ContactUSID = long.Parse(grdUsers.DataKeys[e.NewEditIndex]["ID"].ToString());

        mContactUSID = ContactUSID;

        editLoad();

        e.Cancel = true;

    }
}
